<?php
/*
    Plugin Name: Open Catalog
    Plugin URI: http://www.melky.com
    Description: Open Catalog
    Author: Melky
    Version: 1.0
    Author URI: http://www.melky.com
 
 */

define('PRICE','oc_price');
define('AVAILABLE_NOW','oc_available_now');
define('MINIMUM_PRICE','oc_minimum_price');

function getMetaData(){
  global $post;
  return array(	PRICE=>array(get_post_meta($post->ID,PRICE,true),'text','Precio'),
  				AVAILABLE_NOW=>array(get_post_meta($post->ID,AVAILABLE_NOW,true),'checkbox','Disponible ya'),
  				MINIMUM_PRICE=>array(get_post_meta($post->ID,MINIMUM_PRICE,true),'checkbox','Precio minimo garantizado')
  );
}

function updateMetaData(){
  global $post;    
  $price = $_POST[PRICE];
  $avail = $_POST[AVAILABLE_NOW];
  $minim = $_POST[MINIMUM_PRICE];
  
  if(!update_post_meta($post->ID,PRICE,$price)){
     add_post_meta($post->ID,PRICE,$price, true);
  }
  if(!update_post_meta($post->ID,AVAILABLE_NOW,$avail)){
  	add_post_meta($post->ID,AVAILABLE_NOW,$avail, true);
  }
  if(!update_post_meta($post->ID,MINIMUM_PRICE,$minim)){
  	add_post_meta($post->ID,MINIMUM_PRICE,$minim, true);
  }
}

function openCatalogPanel(){
   add_meta_box('open-catalog-panel', 'Opciones de catalogo', 'showInAdminForm', 'post', 'normal', 'high');
}

function showInAdminForm(){
  $meta_data = getMetaData();
  foreach($meta_data as $key=>$array){
  	$value=$array[0];
  	$type=$array[1];
  	$label=$array[2];
  	echo "<lable>$label</label><input type='$type' id='$key' name='$key' value='$value' />";
  }
}

function get_catalog_price($id){
	global $post;
	$id = !is_null($id) ? $id : $post->ID;
	return get_post_meta($id,PRICE, true);
}
function is_minimum_price($id){
	global $post;
	$id = !is_null($id) ? $id : $post->ID;
	return get_post_meta($id,MINIMUM_PRICE, true)==1;
}
function is_available_now($id){
	global $post;
	$id = !is_null($id) ? $id : $post->ID;
	return get_post_meta($id,AVAILABLE_NOW, true)==1;
}

/* Hooks */

add_action('admin_menu','openCatalogPanel');
add_action('publish_post','updateMetaData' );
add_action('deleted_post','updateMetaData' );
add_action('edit_post','updateMetaData' );

?>
